package main

import (
	"fmt"
	"net"
	"time"
	encoder2 "zinxtcp/default/encoder"
	"zinxtcp/default/message"
)

/*
   模拟客户端
*/
func main() {

	fmt.Println("Client Test ... start")
	//3秒之后发起测试请求，给服务端开启服务的机会
	time.Sleep(3 * time.Second)

	conn, err := net.Dial("tcp", "127.0.0.1:7777")
	if err != nil {
		fmt.Println("client start err, exit!")
		return
	}
	c := conn.(*net.TCPConn)

	encoder := &encoder2.Encoder{}
	unpackFunc := encoder.GetUnpackFunc()
	packFunc := encoder.GetPackFunc()

	for {
		//发封包message消息
		packHeader := message.NewPackHeader(1000)
		data := []byte("Zinx Client 1 route 1000 Test Message")
		dataBytes, err := packFunc(packHeader, data)
		_, err = conn.Write(dataBytes)
		if err != nil {
			fmt.Println("write error err ", err)
			return
		}
		//从链接中获取分包信息
		msg, err := unpackFunc(c)
		if err != nil {
			fmt.Println("server unpack err:", err.Error())
			return
		}
		if msg.GetDataLen() > 0 {
			fmt.Println("==> Recv Msg: ID=", msg.GetMsgId(), ", len=", msg.GetDataLen(), ", data=", string(msg.GetData()))
		}

		time.Sleep(5 * time.Second)
	}
}
